const Koa = require('koa')
const app = new Koa()
 
//引入redis工具模块
const redis = require('./_redis')  

//引入socket
const IO = require('koa-socket')
const url = require('url');



//创建socket对象
const io = new IO() 
//加入到app实例
io.attach(app)  

redis.on('error', (err) => {
  console.log(err);
})


//测试redis
redis.hgetall('iptop10').then(function (result) {
  var city = []
  var cnts = []
   for (var key in result){
     
     city.push(key.trim())
     cnts.push(result[key])
   }
  console.log(city)
  
})


//创建socket监听
app._io.on('connection', socket => {
  console.log('建立连接了');
  var groupid = url.parse(socket.request.url, true).query.groupid;   // 获取分组号
  socket.join(groupid);  // 加入分组
  // 监听客户端连接
  socket.on('clientMsg', async function (data) {
      
      //从redis获取不同省份的ip访问量      
      redis.hgetall('iptop10').then(function (result) {
        var city = []
        var cnts = []  
         for (var key in result){ 
          if(key!='全球'){
            city.push(key.trim())
            cnts.push(parseInt(result[key]))
          }
        
         }

        console.log({"city":city,"cnts":cnts})
        socket.emit('serverMsg', {"city":city,"cnts":cnts});  // 单播：单个socket互不影响，谁给我发的信息我回返回给谁
      }) 
      
  })

})
 
app.listen(3000, () => {
  console.log("my server running at http://localhost:3000")
})
